<template>
  <el-dialog v-el-drag-dialog title="分配用户" :visible.sync="visible" :append-to-body="appendToBody">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item prop="Q_loginName_S_LK">
            <el-input v-model="queryData.Q_loginName_S_LK" placeholder="登录名称" />
          </el-form-item>
          <el-form-item prop="Q_userName_S_LK">
            <el-input v-model="queryData.Q_userName_S_LK" placeholder="用户名称" />
          </el-form-item>
          <el-form-item prop="Q_email_S_LK">
            <el-input v-model="queryData.Q_email_S_LK" placeholder="邮箱" />
          </el-form-item>
          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item m-l-5" type="info" round icon="el-icon-refresh" @click="handleClear">
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['system:role:grant']" size="mini" plain type="primary" icon="el-icon-plus" @click="handleAuth()">
              添加授权用户
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['system:role:grant']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-minus" @click="handleCancel()">
              取消授权用户
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="mini" plain type="info" icon="el-icon-close" @click="handleClose()">
              关闭
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
        </el-row>
        <el-table
          ref="userTable"
          v-loading="tableLoading"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="260px"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column align="center" label="登录名" prop="loginName" sortable width="100" show-overflow-tooltip />
          <el-table-column align="center" label="用户名" prop="userName" sortable width="100" show-overflow-tooltip />
          <el-table-column align="center" label="部门" prop="deptName" width="100" show-overflow-tooltip />
          <el-table-column align="center" label="邮箱" prop="email" show-overflow-tooltip />
          <el-table-column align="center" label="手机" prop="mobile" show-overflow-tooltip />
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>

    <user-select-dialog v-if="openUserDialog" ref="userDialog" :url="userTableUrl" @confirmDialog="authUser" />
  </el-dialog>
</template>

<script>
import { userTable } from '@/api/system/user'
import { addRoleUser, deleteRoleUser } from '@/api/system/role'
import UserSelectDialog from '@/views/system/user/table/selectDialog'

export default {
  name: 'AuthUserDialog',
  components: {
    UserSelectDialog
  },
  data() {
    return {
      visible: false,
      appendToBody: false,
      showSearch: true,
      queryData: {
        roleId: undefined,
        Q_loginName_S_LK: undefined,
        Q_userName_S_LK: undefined,
        Q_email_S_LK: undefined,
        Q_mobile_S_LK: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: 'createTime',
        order: 'asc'
      },
      selectionData: [],
      openUserDialog: false,
      userTableUrl: `${process.env.VUE_APP_MODULE_ADMIN_API}/api/system/user/addRoleTable`
    }
  },
  methods: {
    init(roleId) {
      this.visible = true
      this.queryData.roleId = roleId
      this.$nextTick(() => {
        this.getTableData()
      })
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      userTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleAuth() {
      this.openUserDialog = true
      this.$nextTick(() => {
        this.$refs.userDialog.init(this.queryData.roleId)
      })
    },
    authUser(row) {
      let userIds = row.map(value => value.userId).join(',')
      if (userIds && userIds.length > 1) {
        if (this.tableData.length > 0) {
          userIds += ',' + this.tableData.map(value => value.userId).join(',')
        }
        addRoleUser({
          roleId: this.queryData.roleId,
          userIds: userIds
        }).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.handleFilter()
        }).catch(e => {})
      }
    },
    handleCancel() {
      if (this.selectionData.length === 0) {
        this.$modal.msgWarning('请至少选择一项')
        return
      }
      const ids = this.selectionData.map(user => {
        return user.userId
      }).join(',')
      deleteRoleUser({
        roleId: this.queryData.roleId,
        userIds: ids
      }).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.handleFilter()
      }).catch(e => {})
    },
    handleClose() {
      this.visible = false
      this.$refs.queryForm.resetFields()
      this.tableData = []
      this.tableQuery = {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      }
      this.selectionData = []
    }
  }
}
</script>
